#include "InitializationRoutines.h"
#include "GenerateICode.h"
#include "X86ICode.h"
#include "Symbol.h"
#include "ParseNode.h"
#include <stdio.h>
#include <sys/stat.h>
#ifdef WIN32
	#include <windows.h>
#endif

#ifdef WIN32
    #define DOES_FILE_EXIST(FILEPATH)\
        (GetFileAttributesA(FILEPATH) != INVALID_FILE_ATTRIBUTES)
#else
	INLINE BOOL DoesFileExistForLinux(const char* filePath)
	{
		struct stat fileInfo;

		return (stat(filePath,&fileInfo) == 0);
	}
    #define DOES_FILE_EXIST(FILEPATH)\
        (DoesFileExistForLinux(FILEPATH))
#endif

void InitializeCompiler()
{
	symbols = (struct Symbol*)symbolData;
	icode = (struct Instruction*)icodeData;
	statements = statementData + (STATEMENTS_DATA_SIZE - 1);
	variables = (struct Variable*)variableData;
	x86ICode = (struct X86IOperation*)x86ICodeData;
}

char* IsSourceFilePathInArguments(int argc, char** argv)
{
	if (argc != 1)
	{
		int i;
		for (i = 1; i + 1 <= argc; ++i)
		{
			if (argv[i][0] == '-' && argv[i][1] == 's')
			{
				if (DOES_FILE_EXIST(argv[i + 1]))
				{
					return argv[i + 1];
					break;
				}
				else
				{
				    printf("ERROR: \"%s\" does not exist\n", argv[i + 1]);
				    break;
				}
			}
		}
	}

	return NULL;
}

char* IsExecutableFilePathInArguments(int argc, char** argv)
{
	if (argc != 1)
	{
		int i;
		for (i = 1; i + 1 <= argc; ++i)
		{
			if (argv[i][0] == '-' && argv[i][1] == 'o')
			{
                return argv[i + 1];
                break;
			}
		}
	}

	return NULL;
}

extern FILE *yyin;
int yyparse();

void ParseFile(FILE* file)
{
	yyin = file;
	yyparse();
}

void PrintHelp()
{
	printf("AddCompiler -s \"[SOURCE_FILE_PATH]\" -o \"[EXECUTABLE_FILE_PATH]\"\n");
}
